% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/parallel.R
\name{register}
\alias{register}
\title{Register \code{\link{parallel}} with \code{Make} jobserver}
\usage{
register(tokens = pmax(parallel::detectCores() - 1, 1))
}
\arguments{
\item{tokens}{Maximum number of allowed jobs.}
}
\value{
\code{register} should always return at least 1 and at
    most, \code{tokens} + 1.
}
\description{
When run inside a script spawned by \code{Make}, returns the number
of available jobs that one of the R \code{\link{parallel}}
functions (such as \code{\link[parallel]{mclapply}}) can
spawn. When run outside of Make, simply returns the value of
\code{tokens}.
}
\details{
When running Rscripts with parallelized Make, we run into
    the problem of Make spawning N number of jobs with each Rscript
    then spawning as many child processes as set by
    \code{mc.cores}. \code{register} hooks into Make's jobserver
    and synchronises the spawning of child processes in R with the
    spawning of jobs by Make.

    To do this, we read and write from two file descriptors (rfd,
    wfd) passed by Make in the environmental flag
    \code{--jobserver-auth}. Make will write a token into rfd for
    each job slot available. \code{register} reads those tokens and
    returns the number of slots available for use with
    \code{\link{parallel}} and registers a hook function on
    script exit to write back the tokens to wfd so that the job
    slots are freed up again for Make's jobserver.

    This means that if Make is called with \code{-j5} and two jobs
    have been spawned, in this case both being a hypothetical
    Rscript which will call \code{\link[parallel]{mclapply}}, then
    3 tokens will be available. \code{register} is greedy in that
    the first Rscript to read from rfd will grab all 3 tokens and
    can set mc.cores to 4 (1 job slot for the parent script + 3
    extra), while the second sets mc.cores to only 1.

    If for some reason we want to ensure that R never spawns more
    than N number of child processes, regardless of how many tokens
    are available, we can set the parameter \code{tokens}.
}
\section{Warning}{
 For Make to pass along \code{--jobserver-auth},
    the command in the target rule must be prefixed with '+'.

    Furthermore, it's worth noting that \code{register} will never
    blocking on reading rfd. If there are no tokens available, then
    \code{register} will return 1 immediately. An area of future
    improvement would be to allow for the option of blocking until
    at least N tokens are available. However, you run into the
    obstacle of Make spawning the maximum number of jobs, each of
    which is waiting for say 1 extra token, thereby potentially
    blocking forever.
}

\examples{
options(mc.cores = register())

}
